/**
 * Created by jianglinjie on Tue Oct 10 2017
 * @flow
 */
'use strict';
import * as StorageKeys from '../constants/StorageKeys';
import ConfigService from '../config';
import ClientLog from '../log';
import type { UserInfo, LoginResult } from '../../serviceTypes';

export default class AuthStore {
  async saveLoginResult(result: LoginResult): Promise<void> {
    await ConfigService.storage.save({
      key: StorageKeys.AuthServiceLoginResult,
      data: result,
      expires: null
    });
  }

  async loadLoginResult(): Promise<?LoginResult> {
    try {
      let result = await ConfigService.storage.load({
        key: StorageKeys.AuthServiceLoginResult
      });
      return result;
    } catch (error) {
      return null;
    }
  }

  async removeLoginResult(): Promise<void> {
    try {
      await ConfigService.storage.remove({
        key: StorageKeys.AuthServiceLoginResult
      });
    } catch (error) {
      ClientLog.error('removeLoginResult error %o', error);      
    }
  }

  async addRecentLoginedUserInfo(userInfo: UserInfo): Promise<void> {
    try {
      let preUserInfoList: Array<UserInfo> = await this.getRecentLoginedUserInfos();
      let newUserInfoList = [userInfo];
      for (let preUserInfo of preUserInfoList) {
        if (preUserInfo.uid !== userInfo.uid) {
          //不重复添加
          newUserInfoList.push(preUserInfo);
        }
      }

      await ConfigService.storage.save({
        key: StorageKeys.AuthServiceRecentLoginedUsers,
        data: newUserInfoList,
        expires: null        
      });
    } catch (error) {
      ClientLog.error('loadLoginResult error %o', error);      
    }
  }

  async getRecentLoginedUserInfos(): Promise<Array<UserInfo>> {
    try {
      let userInfos = await ConfigService.storage.load({
        key: StorageKeys.AuthServiceRecentLoginedUsers
      });
      return userInfos || [];
    } catch (error) {
      return [];
    }
  }
}
